package nio;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOSender {
	private static final int BUF_SIZE = 256 * 1024 - 1;

	public static void main(String[] args) throws IOException {
		String serverHostname = new String("127.0.0.1");

		System.out.println("Attemping to connect to host " + serverHostname
				+ " on port 7777.");

		String hostname = "192.168.1.105";
		int port = 7777;

		long start = System.currentTimeMillis();

		try {

			SocketChannel s = SocketChannel.open(new InetSocketAddress(
					hostname, port));
			s.configureBlocking(false);

			ByteBuffer bytes = ByteBuffer.allocateDirect(BUF_SIZE);

			FileInputStream fis = new FileInputStream(new File("data/data.bin"));
			FileChannel fileChannel = fis.getChannel();

			int size = BUF_SIZE + 1;

			ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE);

			int totalSize = 0;
			while (size > 0) {
				buf.clear();
				size = fileChannel.read(buf);
				totalSize += size;
				buf.flip();
				if (size > 0) {
					while (buf.hasRemaining()) {
						s.write(buf);
					}
				}
			}

			System.out.println("Total sent: " + totalSize
					+ "b. Waiting for ACK.");

			ByteBuffer ackBuffer = ByteBuffer.allocate(1);
			ackBuffer.clear();
			s.read(ackBuffer);
			ackBuffer.flip();
			if (ackBuffer.get() == 77) {
				System.out.println("TX verified.");
			}

			long end = System.currentTimeMillis();
			long delta = end - start;
			System.out.println("Total time (net copy NIO): " + delta + " ms.");

			s.close();
			fis.close();

		} catch (RuntimeException ex) {
			System.err.println(ex);

			long end = System.currentTimeMillis();
			long delta = end - start;
			System.out.println("Total time (net copy NIO): " + delta + " ms.");
			
			throw ex;
		}
	}
}